package com.csdj.sc.common.aop;




import com.csdj.sc.common.annonation.Role;
import com.csdj.sc.common.base.WebResult;
import com.csdj.sc.common.constant.WebMsgConstant;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

@Aspect
public abstract class AbstractRoleCheck {

    @Pointcut("@annotation(com.csdj.sc.common.annonation.Role)")
    public void pointcut(){};


    @Around("pointcut()")
    public Object checkRole(ProceedingJoinPoint pjp){
        //通过aop获取被拦截的方法签名
        MethodSignature methodSignature = (MethodSignature)pjp.getSignature();
        //通过反射获取拦截方法上的注解
        Role role = methodSignature.getMethod().getAnnotation(Role.class);
        int[] roles = role.roles();
        if(checkRoles(roles)){
            //权限认证通过
            try {
                return pjp.proceed();
            } catch (Throwable throwable) {
                throwable.printStackTrace();
                return new WebResult(WebMsgConstant.FAIL);
            }
        }else{
            //权限不足
            return new WebResult(WebMsgConstant.NO_AUTH);
        }
    }

    /**
     * 判断用户的权限是否充足
     * @param roles
     * @return
     */
    public abstract boolean checkRoles(int[] roles);
}
